/**
 * JSON数据服务
 * 提供基于JSON的本地数据存储和读取功能
 */
import { User } from './entity/User';
import { Case as CaseEntity } from './entity/Case'; // 重命名以避免与JavaScript保留字冲突
import { Clue } from './entity/Clue';
import { Evidence } from './entity/Evidence';
import { Person } from './entity/Person';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
import { DataInitializer } from './DataInitializer';

export class JSONDataService {
  // 数据存储目录
  private static readonly DATA_DIR: string = this.getDataDir();
  
  // 数据文件路径
  private static readonly FILES = {
    USERS: `${this.DATA_DIR}/users.json`,
    CASES: `${this.DATA_DIR}/cases.json`,
    CLUES: `${this.DATA_DIR}/clues.json`,
    EVIDENCE: `${this.DATA_DIR}/evidence.json`,
    PERSONS: `${this.DATA_DIR}/persons.json`
  };
  
  /**
   * 获取数据存储目录
   * @returns 数据存储目录路径
   */
  private static getDataDir(): string {
    // 在实际应用中，应该使用Context获取应用的data目录
    // 这里使用一个模拟的路径
    // 注意：在真实环境中，需要通过应用上下文获取正确的存储路径
    return '/data/storage/el2/base/ai_detective';
  }
  
  /**
   * 初始化数据服务
   * 创建必要的目录和文件
   */
  public static async initialize(): Promise<void> {
    try {
      console.log('开始初始化JSON数据服务...');
      // 使用异步API替代同步API，避免阻塞主线程
      await this.ensureDirectoryExists();
      
      // 并行初始化各个数据文件，提高性能
      await Promise.all([
        this.initializeFile(this.FILES.USERS, []),
        this.initializeFile(this.FILES.CASES, []),
        this.initializeFile(this.FILES.CLUES, []),
        this.initializeFile(this.FILES.EVIDENCE, []),
        this.initializeFile(this.FILES.PERSONS, [])
      ]);
      
      // 初始化默认数据 - 调用静态方法
      await DataInitializer.initializeDefaultData();
      
      console.log('JSON数据服务初始化成功');
    } catch (error) {
      console.error('JSON数据服务初始化失败:', error);
      throw error;
    }
  }
  
  /**
   * 确保数据目录存在（异步版本）
   */
  private static async ensureDirectoryExists(): Promise<void> {
    try {
      // 尝试访问目录
      await fs.access(this.DATA_DIR);
    } catch (error) {
      // 目录不存在时创建
      if ((error as BusinessError).code === 20) { // 文件不存在错误码
        await fs.mkdir(this.DATA_DIR, 0o777, true);
        console.log(`创建数据目录: ${this.DATA_DIR}`);
      } else {
        throw error;
      }
    }
  }
  
  /**
   * 初始化文件（异步版本）
   * @param filePath 文件路径
   * @param defaultValue 默认值
   */
  private static async initializeFile(filePath: string, defaultValue: any): Promise<void> {
    try {
      try {
        // 尝试访问文件
        await fs.access(filePath);
      } catch (error) {
        // 文件不存在时创建
        if ((error as BusinessError).code === 20) { // 文件不存在错误码
          console.log(`创建数据文件: ${filePath}`);
          
          // 使用异步API操作文件
          const file = await fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
          try {
            // 序列化数据并写入文件
            const jsonString = JSON.stringify(defaultValue, null, 2);
            await fs.write(file.fd, jsonString);
          } finally {
            // 确保文件关闭
            await fs.close(file);
          }
        } else {
          throw error;
        }
      }
    } catch (error) {
      console.error(`初始化文件失败 ${filePath}:`, error);
      throw error;
    }
  }
  
  /**
   * 读取JSON文件（异步优化版本）
   * @param filePath 文件路径
   * @returns 文件内容
   */
  private static async readJsonFile(filePath: string): Promise<any> {
    let file = null;
    try {
      // 先检查文件是否存在
      try {
        await fs.access(filePath);
      } catch (accessError) {
        if ((accessError as BusinessError).code === 20) {
          console.warn(`文件不存在，创建空文件: ${filePath}`);
          await this.initializeFile(filePath, []);
          return [];
        }
        throw accessError;
      }
      
      // 使用异步API打开文件
      file = await fs.open(filePath, fs.OpenMode.READ_ONLY);
      
      // 获取文件信息
      const fileInfo = await fs.stat(filePath);
      
      // 处理空文件情况
      if (fileInfo.size === 0) {
        return [];
      }
      
      // 创建适当大小的缓冲区
      const buffer = new ArrayBuffer(fileInfo.size);
      
      // 读取文件内容
      await fs.read(file.fd, buffer, { offset: 0, length: fileInfo.size });
      
      // 转换缓冲区为字符串
      const decoder = new TextDecoder('utf-8');
      const jsonString = decoder.decode(new Uint8Array(buffer));
      
      // 解析JSON
      return JSON.parse(jsonString);
    } catch (error) {
      console.error(`读取文件失败 ${filePath}:`, error);
      // 返回空数组作为默认值
      return [];
    } finally {
      // 确保文件关闭
      if (file) {
        try {
          await fs.close(file);
        } catch (closeError) {
          console.error(`关闭文件失败 ${filePath}:`, closeError);
        }
      }
    }
  }
  
  /**
   * 写入JSON文件（异步优化版本）
   * @param filePath 文件路径
   * @param data 要写入的数据
   */
  private static async writeJsonFile(filePath: string, data: any): Promise<void> {
    let file = null;
    try {
      // 序列化数据 - 添加日期序列化支持
      const jsonString = JSON.stringify(data, (key, value) => {
        if (value instanceof Date) {
          return value.toISOString();
        }
        return value;
      }, 2);
      
      // 使用异步API打开文件，如果文件不存在则创建
      file = await fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNCATE | fs.OpenMode.CREATE);
      
      // 写入文件
      await fs.write(file.fd, jsonString);
    } catch (error) {
      console.error(`写入文件失败 ${filePath}:`, error);
      throw error;
    } finally {
      // 确保文件关闭
      if (file) {
        try {
          await fs.close(file);
        } catch (closeError) {
          console.error(`关闭文件失败 ${filePath}:`, closeError);
        }
      }
    }
  }
  
  // ========== 用户相关操作 ==========
  
  /**
   * 获取所有用户
   * @returns 用户列表
   */
  public static async getAllUsers(): Promise<User[]> {
    try {
      const users = await this.readJsonFile(this.FILES.USERS);
      return users.map((u: any) => User.fromJSON(u));
    } catch (error) {
      console.error('获取用户列表失败:', error);
      return [];
    }
  }
  
  /**
   * 添加用户
   * @param user 用户对象
   * @returns 添加的用户
   */
  public static async createUser(user: User): Promise<User> {
    try {
      const users = await this.readJsonFile(this.FILES.USERS);
      users.push(user.toJSON());
      await this.writeJsonFile(this.FILES.USERS, users);
      return user;
    } catch (error) {
      console.error('添加用户失败:', error);
      throw error;
    }
  }
  
  /**
   * 根据用户名获取用户
   * @param username 用户名
   * @returns 用户对象或null
   */
  public static async getUserByUsername(username: string): Promise<User | null> {
    try {
      const users = await this.readJsonFile(this.FILES.USERS);
      const userData = users.find((u: any) => u.username === username);
      return userData ? User.fromJSON(userData) : null;
    } catch (error) {
      console.error('获取用户失败:', error);
      return null;
    }
  }
  
  /**
   * 更新用户
   * @param user 用户对象
   * @returns 更新后的用户
   */
  public static async updateUser(user: User): Promise<User> {
    try {
      const users = await this.readJsonFile(this.FILES.USERS);
      const index = users.findIndex((u: any) => u.id === user.id);
      
      if (index !== -1) {
        users[index] = user.toJSON();
        await this.writeJsonFile(this.FILES.USERS, users);
        console.log(`用户更新成功: ${user.username} (ID: ${user.id})`);
      } else {
        console.warn(`未找到要更新的用户: ${user.id}`);
      }
      
      return user;
    } catch (error) {
      console.error('更新用户失败:', error);
      throw new Error(`更新用户失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 删除用户
   * @param id 用户ID
   * @returns 是否删除成功
   */
  public static async deleteUser(id: string): Promise<boolean> {
    try {
      const users = await this.readJsonFile(this.FILES.USERS);
      const filteredUsers = users.filter((u: any) => u.id !== id);
      
      if (filteredUsers.length !== users.length) {
        await this.writeJsonFile(this.FILES.USERS, filteredUsers);
        console.log(`用户删除成功: ${id}`);
        return true;
      }
      
      console.warn(`未找到要删除的用户: ${id}`);
      return false;
    } catch (error) {
      console.error('删除用户失败:', error);
      throw new Error(`删除用户失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 根据ID获取用户
   * @param id 用户ID
   * @returns 用户对象或null
   */
  public static async getUserById(id: string): Promise<User | null> {
    try {
      const users = await this.readJsonFile(this.FILES.USERS);
      const userData = users.find((u: any) => u.id === id);
      return userData ? User.fromJSON(userData) : null;
    } catch (error) {
      console.error(`获取用户失败: ${id}`, error);
      return null;
    }
  }
  
  // ========== 案件相关操作 ==========
  
  /**
   * 添加案件
   * @param caseData 案件对象
   * @returns 添加的案件
   */
  public static async createCase(caseData: CaseEntity): Promise<CaseEntity> {
    try {
      const cases = await this.readJsonFile(this.FILES.CASES);
      
      // 为案件生成唯一ID（如果没有）
      if (!caseData.id) {
        caseData.id = Date.now().toString() + '_' + Math.random().toString(36).substr(2, 9);
      }
      
      cases.push(caseData.toJSON());
      await this.writeJsonFile(this.FILES.CASES, cases);
      return caseData;
    } catch (error) {
      console.error('添加案件失败:', error);
      throw error;
    }
  }
  
  /**
   * 获取所有案件
   * @returns 案件列表
   */
  public static async getAllCases(): Promise<CaseEntity[]> {
    try {
      const cases = await this.readJsonFile(this.FILES.CASES);
      return cases.map((c: any) => CaseEntity.fromJSON(c));
    } catch (error) {
      console.error('获取案件列表失败:', error);
      return [];
    }
  }
  
  /**
   * 根据ID获取案件
   * @param id 案件ID
   * @returns 案件对象或null
   */
  public static async getCaseById(id: string): Promise<CaseEntity | null> {
    try {
      const cases = await this.readJsonFile(this.FILES.CASES);
      const caseData = cases.find((c: any) => c.id === id);
      return caseData ? CaseEntity.fromJSON(caseData) : null;
    } catch (error) {
      console.error('获取案件失败:', error);
      return null;
    }
  }
  
  /**
   * 更新案件
   * @param caseData 案件对象
   * @returns 更新后的案件
   */
  public static async updateCase(caseData: CaseEntity): Promise<CaseEntity> {
    try {
      const cases = await this.readJsonFile(this.FILES.CASES);
      const index = cases.findIndex((c: any) => c.id === caseData.id);
      
      if (index !== -1) {
        // 更新最后修改时间
        caseData.updatedAt = new Date();
        
        cases[index] = caseData.toJSON();
        await this.writeJsonFile(this.FILES.CASES, cases);
        console.log(`案件更新成功: ${caseData.title} (ID: ${caseData.id})`);
      } else {
        console.warn(`未找到要更新的案件: ${caseData.id}`);
      }
      
      return caseData;
    } catch (error) {
      console.error('更新案件失败:', error);
      throw new Error(`更新案件失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 删除案件
   * @param id 案件ID
   * @returns 是否删除成功
   */
  public static async deleteCase(id: string): Promise<boolean> {
    try {
      // 开始事务式删除，先检查案件是否存在
      const caseData = await this.getCaseById(id);
      if (!caseData) {
        console.warn(`未找到要删除的案件: ${id}`);
        return false;
      }
      
      // 并行删除相关数据以提高性能
      await Promise.all([
        // 删除案件
        (async () => {
          const cases = await this.readJsonFile(this.FILES.CASES);
          const filteredCases = cases.filter((c: any) => c.id !== id);
          await this.writeJsonFile(this.FILES.CASES, filteredCases);
        })(),
        
        // 删除相关线索
        (async () => {
          const clues = await this.readJsonFile(this.FILES.CLUES);
          const filteredClues = clues.filter((c: any) => c.caseId !== id);
          await this.writeJsonFile(this.FILES.CLUES, filteredClues);
        })(),
        
        // 删除相关证据
        (async () => {
          const evidences = await this.readJsonFile(this.FILES.EVIDENCE);
          const filteredEvidences = evidences.filter((e: any) => e.caseId !== id);
          await this.writeJsonFile(this.FILES.EVIDENCE, filteredEvidences);
        })(),
        
        // 从人员关联中移除案件ID
        (async () => {
          const persons = await this.readJsonFile(this.FILES.PERSONS);
          const updatedPersons = persons.map((p: any) => {
            // 处理不同的属性名情况
            if (p.relatedCaseIds && Array.isArray(p.relatedCaseIds)) {
              p.relatedCaseIds = p.relatedCaseIds.filter((cid: string) => cid !== id);
            } else if (p.relatedCases && Array.isArray(p.relatedCases)) {
              p.relatedCases = p.relatedCases.filter((cid: string) => cid !== id);
            }
            return p;
          });
          await this.writeJsonFile(this.FILES.PERSONS, updatedPersons);
        })()
      ]);
      
      console.log(`案件及其相关数据删除成功: ${id}`);
      return true;
    } catch (error) {
      console.error('删除案件失败:', error);
      throw new Error(`删除案件失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // ========== 线索相关操作 ==========
  
  /**
   * 添加线索
   * @param clue 线索对象
   * @returns 添加的线索
   */
  public static async createClue(clue: Clue): Promise<Clue> {
    try {
      const clues = await this.readJsonFile(this.FILES.CLUES);
      clues.push(clue.toJSON());
      await this.writeJsonFile(this.FILES.CLUES, clues);
      
      // 同时更新案件中的线索ID列表
      const caseData = await this.getCaseById(clue.caseId);
      if (caseData) {
        caseData.addClue(clue.id);
        await this.updateCase(caseData);
      }
      
      return clue;
    } catch (error) {
      console.error('添加线索失败:', error);
      throw error;
    }
  }
  
  /**
   * 获取案件的所有线索
   * @param caseId 案件ID
   * @returns 线索列表
   */
  public static async getCluesByCaseId(caseId: string): Promise<Clue[]> {
    try {
      const clues = await this.readJsonFile(this.FILES.CLUES);
      const caseClues = clues.filter((c: any) => c.caseId === caseId);
      return caseClues.map((c: any) => Clue.fromJSON(c));
    } catch (error) {
      console.error('获取线索列表失败:', error);
      return [];
    }
  }
  
  /**
   * 更新线索
   * @param clue 线索对象
   * @returns 更新后的线索
   */
  public static async updateClue(clue: Clue): Promise<Clue> {
    try {
      const clues = await this.readJsonFile(this.FILES.CLUES);
      const index = clues.findIndex((c: any) => c.id === clue.id);
      
      if (index !== -1) {
        clues[index] = clue.toJSON();
        await this.writeJsonFile(this.FILES.CLUES, clues);
        console.log(`线索更新成功: ${clue.title} (ID: ${clue.id})`);
      } else {
        console.warn(`未找到要更新的线索: ${clue.id}`);
      }
      
      return clue;
    } catch (error) {
      console.error('更新线索失败:', error);
      throw new Error(`更新线索失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 删除线索
   * @param id 线索ID
   * @returns 是否删除成功
   */
  public static async deleteClue(id: string): Promise<boolean> {
    try {
      // 先获取线索以找到关联的案件ID
      const clues = await this.readJsonFile(this.FILES.CLUES);
      const clueIndex = clues.findIndex((c: any) => c.id === id);
      
      if (clueIndex !== -1) {
        const clue = clues[clueIndex];
        
        // 并行执行删除操作
        await Promise.all([
          // 从线索列表中删除
          (async () => {
            const filteredClues = clues.filter((c: any) => c.id !== id);
            await this.writeJsonFile(this.FILES.CLUES, filteredClues);
          })(),
          
          // 从案件的线索列表中移除
          (async () => {
            const caseData = await this.getCaseById(clue.caseId);
            if (caseData && caseData.removeClue) {
              caseData.removeClue(id);
              await this.updateCase(caseData);
            }
          })()
        ]);
        
        console.log(`线索删除成功: ${id}`);
        return true;
      }
      
      console.warn(`未找到要删除的线索: ${id}`);
      return false;
    } catch (error) {
      console.error('删除线索失败:', error);
      throw new Error(`删除线索失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // ========== 证据相关操作 ==========
  
  /**
   * 添加证据
   * @param evidence 证据对象
   * @returns 添加的证据
   */
  public static async createEvidence(evidence: Evidence): Promise<Evidence> {
    try {
      const evidences = await this.readJsonFile(this.FILES.EVIDENCE);
      evidences.push(evidence.toJSON());
      await this.writeJsonFile(this.FILES.EVIDENCE, evidences);
      
      // 同时更新案件中的证据ID列表
      const caseData = await this.getCaseById(evidence.caseId);
      if (caseData) {
        caseData.addEvidence(evidence.id);
        await this.updateCase(caseData);
      }
      
      return evidence;
    } catch (error) {
      console.error('添加证据失败:', error);
      throw error;
    }
  }
  
  /**
   * 获取案件的所有证据
   * @param caseId 案件ID
   * @returns 证据列表
   */
  public static async getEvidencesByCaseId(caseId: string): Promise<Evidence[]> {
    try {
      const evidences = await this.readJsonFile(this.FILES.EVIDENCE);
      const caseEvidences = evidences.filter((e: any) => e.caseId === caseId);
      return caseEvidences.map((e: any) => Evidence.fromJSON(e));
    } catch (error) {
      console.error('获取证据列表失败:', error);
      return [];
    }
  }
  
  /**
   * 更新证据
   * @param evidence 证据对象
   * @returns 更新后的证据
   */
  public static async updateEvidence(evidence: Evidence): Promise<Evidence> {
    try {
      const evidences = await this.readJsonFile(this.FILES.EVIDENCE);
      const index = evidences.findIndex((e: any) => e.id === evidence.id);
      
      if (index !== -1) {
        evidences[index] = evidence.toJSON();
        await this.writeJsonFile(this.FILES.EVIDENCE, evidences);
        console.log(`证据更新成功: ${evidence.name} (ID: ${evidence.id})`);
      } else {
        console.warn(`未找到要更新的证据: ${evidence.id}`);
      }
      
      return evidence;
    } catch (error) {
      console.error('更新证据失败:', error);
      throw new Error(`更新证据失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 删除证据
   * @param id 证据ID
   * @returns 是否删除成功
   */
  public static async deleteEvidence(id: string): Promise<boolean> {
    try {
      // 先获取证据以找到关联的案件ID
      const evidences = await this.readJsonFile(this.FILES.EVIDENCE);
      const evidenceIndex = evidences.findIndex((e: any) => e.id === id);
      
      if (evidenceIndex !== -1) {
        const evidence = evidences[evidenceIndex];
        
        // 并行执行删除操作
        await Promise.all([
          // 从证据列表中删除
          (async () => {
            const filteredEvidences = evidences.filter((e: any) => e.id !== id);
            await this.writeJsonFile(this.FILES.EVIDENCE, filteredEvidences);
          })(),
          
          // 从案件的证据列表中移除
          (async () => {
            const caseData = await this.getCaseById(evidence.caseId);
            if (caseData && caseData.removeEvidence) {
              caseData.removeEvidence(id);
              await this.updateCase(caseData);
            }
          })()
        ]);
        
        console.log(`证据删除成功: ${id}`);
        return true;
      }
      
      console.warn(`未找到要删除的证据: ${id}`);
      return false;
    } catch (error) {
      console.error('删除证据失败:', error);
      throw new Error(`删除证据失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // ========== 人员相关操作 ==========
  
  /**
   * 添加人员
   * @param person 人员对象
   * @returns 添加的人员
   */
  public static async createPerson(person: Person): Promise<Person> {
    try {
      const persons = await this.readJsonFile(this.FILES.PERSONS);
      persons.push(person.toJSON());
      await this.writeJsonFile(this.FILES.PERSONS, persons);
      return person;
    } catch (error) {
      console.error('添加人员失败:', error);
      throw error;
    }
  }
  
  /**
   * 获取案件相关的所有人员
   * @param caseId 案件ID
   * @returns 人员列表
   */
  public static async getPersonsByCaseId(caseId: string): Promise<Person[]> {
    try {
      const persons = await this.readJsonFile(this.FILES.PERSONS);
      const casePersons = persons.filter((p: any) => p.relatedCaseIds?.includes(caseId));
      return casePersons.map((p: any) => Person.fromJSON(p));
    } catch (error) {
      console.error('获取人员列表失败:', error);
      return [];
    }
  }
  
  /**
   * 更新人员
   * @param person 人员对象
   * @returns 更新后的人员
   */
  public static async updatePerson(person: Person): Promise<Person> {
    try {
      const persons = await this.readJsonFile(this.FILES.PERSONS);
      const index = persons.findIndex((p: any) => p.id === person.id);
      
      if (index !== -1) {
        persons[index] = person.toJSON();
        await this.writeJsonFile(this.FILES.PERSONS, persons);
        console.log(`人员更新成功: ${person.name} (ID: ${person.id})`);
      } else {
        console.warn(`未找到要更新的人员: ${person.id}`);
      }
      
      return person;
    } catch (error) {
      console.error('更新人员失败:', error);
      throw new Error(`更新人员失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 删除人员
   * @param id 人员ID
   * @returns 是否删除成功
   */
  public static async deletePerson(id: string): Promise<boolean> {
    try {
      const persons = await this.readJsonFile(this.FILES.PERSONS);
      const filteredPersons = persons.filter((p: any) => p.id !== id);
      
      if (filteredPersons.length !== persons.length) {
        await this.writeJsonFile(this.FILES.PERSONS, filteredPersons);
        console.log(`人员删除成功: ${id}`);
        return true;
      }
      
      console.warn(`未找到要删除的人员: ${id}`);
      return false;
    } catch (error) {
      console.error('删除人员失败:', error);
      throw new Error(`删除人员失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 获取统计信息
   * @returns 统计信息
   */
  public static async getStatistics(): Promise<{
    totalUsers: number;
    totalCases: number;
    totalClues: number;
    totalEvidence: number;
    totalPersons: number;
  }> {
    try {
      console.log('获取统计信息中...');
      
      // 并行获取所有数据以提高性能
      const [users, cases, clues, evidence, persons] = await Promise.all([
        this.readJsonFile(this.FILES.USERS),
        this.readJsonFile(this.FILES.CASES),
        this.readJsonFile(this.FILES.CLUES),
        this.readJsonFile(this.FILES.EVIDENCE),
        this.readJsonFile(this.FILES.PERSONS)
      ]);
      
      // 确保返回的是数组类型
      const stats = {
        totalUsers: Array.isArray(users) ? users.length : 0,
        totalCases: Array.isArray(cases) ? cases.length : 0,
        totalClues: Array.isArray(clues) ? clues.length : 0,
        totalEvidence: Array.isArray(evidence) ? evidence.length : 0,
        totalPersons: Array.isArray(persons) ? persons.length : 0
      };
      
      console.log('获取统计信息成功:', stats);
      return stats;
    } catch (error) {
      console.error('获取统计信息失败:', error);
      // 返回默认值
      return {
        totalUsers: 0,
        totalCases: 0,
        totalClues: 0,
        totalEvidence: 0,
        totalPersons: 0
      };
    }
  }
  
  /**
   * 批量创建实体
   * @param entityType 实体类型
   * @param entities 实体数组
   * @returns 创建的实体数量
   */
  public static async bulkCreate<T extends User | CaseEntity | Clue | Evidence | Person>(
    entityType: 'users' | 'cases' | 'clues' | 'evidence' | 'persons',
    entities: T[]
  ): Promise<number> {
    try {
      // 输入验证
      if (!entities || entities.length === 0) {
        console.log('批量创建实体失败: 实体数组为空');
        return 0;
      }
      
      // 确定文件路径 - 使用对象映射替代switch，提高性能
      const filePaths = {
        users: this.FILES.USERS,
        cases: this.FILES.CASES,
        clues: this.FILES.CLUES,
        evidence: this.FILES.EVIDENCE,
        persons: this.FILES.PERSONS
      };
      
      const filePath = filePaths[entityType];
      if (!filePath) {
        throw new Error(`不支持的实体类型: ${entityType}`);
      }
      
      // 获取现有数据
      const existingData = await this.readJsonFile(filePath);
      
      // 转换实体为JSON格式并添加到现有数据
      const newData = entities.map(entity => {
        // 为没有ID的实体生成唯一ID
        if (!entity.id) {
          entity.id = Date.now().toString() + '_' + Math.random().toString(36).substring(2, 11);
        }
        
        // 确保有创建时间
        if (typeof entity === 'object' && !entity.createdAt && entityType !== 'clues' && entityType !== 'evidence') {
          (entity as any).createdAt = new Date();
        }
        
        return entity.toJSON ? entity.toJSON() : entity;
      });
      
      // 合并并写入文件
      const mergedData = [...existingData, ...newData];
      await this.writeJsonFile(filePath, mergedData);
      
      console.log(`批量创建${entityType}成功，创建了${newData.length}个实体`);
      return newData.length;
    } catch (error) {
      console.error(`批量创建${entityType}失败:`, error);
      throw error;
    }
  }
}